package com.benmei.weike.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMailUtil {
    public static final Logger logger = LoggerFactory.getLogger(SendMailUtil.class);
    final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /**
     * @param email
     * @param subject
     * @param content
     * @return
     */
    public static String sendMail(String email, String subject, String content) {
        String result = "1";
        try {
            Properties props = System.getProperties();

            props.setProperty("mail.smtp.host", "smtpdm.aliyun.com");

            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);

            props.setProperty("mail.smtp.socketFactory.fallback", "false");

            props.setProperty("mail.smtp.port", "465");

            props.setProperty("mail.smtp.socketFactory.port", "465");

            props.put("mail.smtp.auth", "true");

            final String username = "nativetalk@mail.app.waijiaojun.com";

            final String pawd = "1234qwerQWER";

            Session mailSession = Session.getDefaultInstance(props, new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {

                    return new PasswordAuthentication(username, pawd);

                }
            });

            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress to = new InternetAddress(email);
            message.setRecipient(RecipientType.TO, to);

            // 设置邮件标题
            if (StringUtils.isBlank(subject)) {
                message.setSubject("Registration Confirmation");
            } else {
                message.setSubject(subject);
            }
            message.setContent(content, "text/html;charset=UTF-8");
            logger.info("发送邮件 --> to:" + email + ",content:" + content);
            // 发送邮件
            Transport.send(message);
            logger.info("发送邮件 --> to:" + email + " 成功");
            result = "0";
        } catch (Exception e) {
            logger.error("发送邮件 --> to:" + email + " 失败");
            logger.error("======error:" + "logInfo" + e.toString() + "======");
        }
        return result;
    }

    public static void main(String[] args) {
        sendMail("3307551249@qq.com","test2","123456  test");
    }
}